/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useRef, useState } from 'react';
import { useAntdTable, useDebounceFn } from 'ahooks';
import { Form, Row, Col, Button, message, Popconfirm } from 'antd';
import StandardTable from '@/components/StandardTable';
import {
  getSendSetting,
  getCourierInfo,
  addCourierInfo,
  deleteCourierInfo,
} from '@/services/allocation';
import KbSelect from '@/components/KbSelect';
import { useSelector } from 'dva';
import { getLStorage } from '@/utils/utils';
import styles from '../style.less';

const FormItem = Form.Item;

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 18 },
  },
};

/**
 * 发派扫描
 *  */
const SendSetting = ({ form, setRecord: { brand, branch_code, brand_name }, showDetail }) => {
  const { validateFields, getFieldDecorator, resetFields } = form;
  const tableList = useRef([]);
  const [adding, setAdding] = useState(false);

  const { user_info = {} } = useSelector(({ user }) => user.currentUser);
  const { gp_area_ids = [], phone, area_ids } = user_info;

  const isCompany = area_ids == '*';
  const cacheAreaId = getLStorage(`KB_GP_AREA_${phone}`);
  const area_id = gp_area_ids.includes(cacheAreaId)
    ? cacheAreaId
    : isCompany
      ? '0'
      : gp_area_ids[0];

  const getTableList = async () => {
    const { list = [] } = await getSendSetting({ brand: brand_name, branch_code, area_id });
    tableList.current = list;
    return {
      list,
      total: list.length,
    };
  };

  const { tableProps, search, loading } = useAntdTable(getTableList, {
    defaultPageSize: 200,
    defaultParams: [{ current: 1, pageSize: 200 }],
    form,
  });

  const onDelete = gp_send_config_id =>
    deleteCourierInfo({
      gp_send_config_id,
      area_id,
    }).then((res = {}) => {
      if (res.code == 0) {
        search.submit();
        message.success('删除成功');
      } else {
        message.error(res.msg);
      }
    });

  const columns = [
    {
      width: 100,
      align: 'center',
      title: '手机号',
      dataIndex: 'cm_phone',
    },
    {
      width: 100,
      align: 'center',
      title: '姓名',
      dataIndex: 'cm_name',
    },
    {
      width: 100,
      align: 'center',
      title: '网点编号',
      dataIndex: 'branch_code',
    },
    {
      width: 100,
      align: 'center',
      title: '工号',
      dataIndex: 'gun_account',
    },
    {
      width: 100,
      align: 'center',
      title: '操作',
      render: (_, data) => (
        <Popconfirm title="确认删除该业务员？" onConfirm={() => onDelete(data.id)}>
          <a>删除</a>
        </Popconfirm>
      ),
    },
  ];

  const { run: onSubmit } = useDebounceFn(
    e => {
      e.preventDefault();
      validateFields(async (err, values) => {
        if (err) return;
        if (tableList.current.length > 0) {
          message.warn('不允许添加多个发件扫描业务员');
          return;
        }
        if (!values.gp_user_config_id) {
          message.error('请选择发件扫描业务员');
          return;
        }
        setAdding(true);
        const { code, msg } = await addCourierInfo({ ...values, branch_code, area_id });
        if (code == 0) {
          search.submit();
          message.success('添加成功');
          resetFields();
        } else {
          message.error(msg);
        }
        setAdding(false);
      });
    },
    {
      wait: 300,
      leading: true,
      trailing: false,
    },
  );

  return (
    <div>
      <Row type="flex" justify="space-between" align="middle" style={{ marginBottom: 24 }}>
        <Col span={18} className={styles.title}>
          <Form layout="inline" {...formItemLayout}>
            <FormItem>
              {getFieldDecorator('gp_user_config_id')(
                <KbSelect
                  allowClear
                  placeholder="请选择发件扫描业务员"
                  style={{ width: 250 }}
                  request={() => getCourierInfo({ brand: brand_name, branch_code, area_id })}
                  label={val => `${val.gun_account}-${val.courier_name}`}
                  format="gp_user_config_id*courier_name"
                />,
              )}
            </FormItem>
            <FormItem>
              <Button type="primary" onClick={onSubmit} loading={adding}>
                添加
              </Button>
            </FormItem>
          </Form>
        </Col>
        <Col span={6}>
          <Row type="flex" align="middle" justify="end">
            <Col>
              <span>{brand}</span>
              <span>（{branch_code}）</span>
            </Col>
            <Col>
              <Button type="primary" onClick={() => showDetail(false)}>
                返回
              </Button>
            </Col>
          </Row>
        </Col>
      </Row>
      <StandardTable
        columns={columns}
        loading={loading}
        rowKey="cm_phone"
        data={{
          list: tableProps.dataSource,
          pagination: {
            ...tableProps.pagination,
            showQuickJumper: false,
            showSizeChanger: false,
          },
        }}
      />
    </div>
  );
};

export default Form.create()(SendSetting);
